﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using RoadFlow.Utility;

namespace RoadFlow.IntegrateCore.Areas.RoadFlowCore.Controllers
{
    [Area("RoadFlowCore")]
    public class MessageController : Controller
    {
        [Validate]
        public IActionResult Index()
        {
            return View();
        }

        [Validate]
        public IActionResult Send()
        {
            ViewData["queryString"] = Request.UrlQuery();
            return View();
        }

        [Validate]
        [ValidateAntiForgeryToken]
        public string SaveSend()
        {
            string ReceiverId = Request.Forms("ReceiverId");
            string ReceiveType = Request.Forms("ReceiveType");
            string Contents = Request.Forms("Contents");
            string Files = Request.Forms("Files");

            if (ReceiverId.IsNullOrWhiteSpace() || ReceiveType.IsNullOrWhiteSpace() || Contents.IsNullOrWhiteSpace())
            {
                return "必填数据不能为空!";
            }
            Model.Message messageModel = new Model.Message
            {
                Contents = Contents,
                Files = Files,
                Id = Guid.NewGuid(),
                ReceiverIdString = ReceiverId,
                SenderId = Current.UserId,
                SenderName = Current.UserName,
                SendType = ReceiveType,
                SendTime = DateExtensions.Now,
                Type = 0
            };
            string msg = new Business.Message().Send(messageModel);
            return "1".Equals(msg) ? "发送成功!" : msg;
        }

        /// <summary>
        /// 发送记录
        /// </summary>
        /// <returns></returns>
        [Validate]
        public IActionResult SendList()
        {
            ViewData["queryString"] = Request.UrlQuery();
            ViewData["tabId"] = Request.Querys("tabid");
            return View();
        }

        /// <summary>
        /// 查询发送记录
        /// </summary>
        /// <returns></returns>
        [Validate]
        public string QuerySendList()
        {
            string sidx = Request.Forms("sidx");
            string sord = Request.Forms("sord");
            int size = Tools.GetPageSize();
            int number = Tools.GetPageNumber();
            bool isAsc = "asc".EqualsIgnoreCase(sord);
            string order = (sidx.IsNullOrEmpty() ? "SendTime" : sidx) + " " + (sord.IsNullOrEmpty() ? "DESC" : sord);

            string Contents = Request.Forms("Contents");
            string Date1 = Request.Forms("Date1");
            string Date2 = Request.Forms("Date2");
            string status = Request.Forms("status");
            string userId = Current.UserId.ToString();
            Business.Message message = new Business.Message();
            System.Data.DataTable dt = message.GetSendList(out int count, size, number, userId, Contents, Date1, Date2, status, order);
            Newtonsoft.Json.Linq.JArray jArray = new Newtonsoft.Json.Linq.JArray();
            foreach (System.Data.DataRow dr in dt.Rows)
            {
                string content = dr["Contents"].ToString();
                Newtonsoft.Json.Linq.JObject jObject = new Newtonsoft.Json.Linq.JObject
                {
                    { "id", dr["Id"].ToString() },
                    { "Contents", "<a class=\"blue\" href=\"javascript:void(0);\" onclick=\"show('" + dr["Id"].ToString() + "');return false;\">"+content.RemoveHTML().Trim1().CutOut(60)+"</a>" },
                    { "SenderName", dr["SenderName"].ToString() },
                    { "SendTime", dr["SendTime"].ToString().ToDateTime().ToDateTimeString() },
                    { "SendType", message.GetSendTypeString(dr["SendType"].ToString()) },
                    { "Files", dr["Files"].ToString().ToFilesShowString(false) },
                    { "Opation", "<a class=\"list\" href=\"javascript:void(0);\" onclick=\"show('" + dr["Id"].ToString() + "');return false;\"><i class=\"fa fa-eye\"></i>查看</a>" }
                };
                jArray.Add(jObject);
            }
            return "{\"userdata\":{\"total\":" + count + ",\"pagesize\":" + size + ",\"pagenumber\":" + number + "},\"rows\":" + jArray.ToString() + "}";
        }

        /// <summary>
        /// 查看已发送消息
        /// </summary>
        /// <returns></returns>
        [Validate]
        public IActionResult SendShow()
        {
            string msgId = Request.Querys("messageid");
            var messageModel = new Business.Message().Get(msgId.ToGuid());
            if (null == messageModel)
            {
                return new ContentResult() { Content= "没有找到该消息!" };
            }
            string showreadlist = Request.Querys("showreadlist");
            if (!"1".Equals(showreadlist))//更新状态为已读
            {
                new Business.MessageUser().UpdateIsRead(messageModel.Id, Current.UserId);
            }
            ViewData["queryString"] = Request.UrlQuery();
            ViewData["showreadlist"] = showreadlist;
            return View(messageModel);
        }
        /// <summary>
        /// 查询阅读人员列表
        /// </summary>
        /// <returns></returns>
        [Validate]
        public string QuerySendRead()
        {
            string sidx = Request.Forms("sidx");
            string sord = Request.Forms("sord");
            int size = Tools.GetPageSize();
            int number = Tools.GetPageNumber();
            bool isAsc = "asc".EqualsIgnoreCase(sord);
            string order = (sidx.IsNullOrEmpty() ? "UserId" : sidx) + " " + (sord.IsNullOrEmpty() ? "ASC" : sord);
            string msgId = Request.Querys("messageid");
            Business.MessageUser messageUser = new Business.MessageUser();
            Business.Organize organize = new Business.Organize();
            Business.User user = new Business.User();
            System.Data.DataTable dt = messageUser.GetReadUserList(out int count, size, number, msgId, order);
            Newtonsoft.Json.Linq.JArray jArray = new Newtonsoft.Json.Linq.JArray();
            foreach (System.Data.DataRow dr in dt.Rows)
            {
                Newtonsoft.Json.Linq.JObject jObject = new Newtonsoft.Json.Linq.JObject
                {
                    { "UserId", user.GetName(dr["UserId"].ToString().ToGuid())},
                    { "Organize", user.GetOrganizeMainShowHtml(dr["UserId"].ToString().ToGuid()) },
                    { "IsRead", dr["IsRead"].ToString().Equals("0")?"未读":"已读" },
                    { "ReadTime", dr["ReadTime"].ToString().IsDateTime(out DateTime d) ? d.ToDateTimeString() : "" }
                };
                jArray.Add(jObject);
            }
            return "{\"userdata\":{\"total\":" + count + ",\"pagesize\":" + size + ",\"pagenumber\":" + number + "},\"rows\":" + jArray.ToString() + "}";
        }

        /// <summary>
        /// 未读消息
        /// </summary>
        /// <returns></returns>
        [Validate(CheckApp = false, CheckUrl = false)]
        public IActionResult NoRead()
        {
            ViewData["tabId"] = Request.Querys("tabid");
            ViewData["queryString"] = Request.UrlQuery();
            return View();
        }

        /// <summary>
        /// 已读消息
        /// </summary>
        /// <returns></returns>
        [Validate(CheckApp = false, CheckUrl = false)]
        public IActionResult ReadList()
        {
            ViewData["tabId"] = Request.Querys("tabid");
            ViewData["queryString"] = Request.UrlQuery();
            return View();
        }

        /// <summary>
        /// 将选择消息标记为已读
        /// </summary>
        /// <returns></returns>
        [Validate(CheckApp = false)]
        public string UpdateRead()
        {
            string ids = Request.Forms("ids");
            Guid userId = Current.UserId;
            Business.MessageUser messageUser = new Business.MessageUser();
            foreach (string id in ids.Split(','))
            {
                if (!id.IsGuid(out Guid mid))
                {
                    continue;
                }
                messageUser.UpdateIsRead(mid, userId);
            }
            return "标记成功!";
        }
    }


}